package temporaryCache

import (
	"git.huoys.com/block_chain/mall/pkg/redisCache/common"
	"time"
)

// 添加哈希缓存
func (c temporaryCache) HashCacheAddMultiple(key string, value map[string]interface{}, cacheTtl, lockTtl time.Duration, requestId int) (err error) {
	var (
		tx      = c.redis.TxPipeline()
		command = make(map[string]interface{})
	)
	for k, v := range value {
		js, err := common.Marshal(v)
		if err != nil {
			return err
		}
		command[k] = js
	}
	// 等待锁释放
	err = c.WaitLock(key)
	if err != nil {
		return err
	}
	// 添加锁
	_, err = c.TryLock(key, requestId, lockTtl)
	defer c.UnLock(key, requestId)
	if err != nil {
		return err
	}
	tx.HMSet(key, command)
	tx.Expire(key, cacheTtl)
	_, err = tx.Exec()
	if err != nil {
		tx.Discard()
	}
	return err
}

// 获取哈希所有key
func (c temporaryCache) HashCacheGetAllKey(key string) (keyExist bool, result []string, err error) {
	exist, err := c.Exist(key)
	if err != nil || !exist {
		return false, nil, err
	}
	// 获取数据
	result, err = c.redis.HKeys(key).Result()
	return
}

// 获取哈希单条key
func (c temporaryCache) HashCacheGet(key, hashKey string) (keyExist bool, result []byte, err error) {
	exist, err := c.Exist(key)
	if err != nil || !exist {
		return false, nil, err
	}
	result, err = c.redis.HGet(key, hashKey).Bytes()
	return
}

// 获取哈希所有键值对
func (c temporaryCache) HashGetAll(key string) (result map[string]string, err error) {
	return c.redis.HGetAll(key).Result()
}
